import { LineLayer, PolygonLayer, PointLayer, Control, Layers, Popup } from '@antv/l7';

const colors = ['#eef2f4', '#aab9c0', '#d0f3fd', '#9de7fa', '#00c1f2'];

// 图层颜色
export function addLayerGroup(scene, data, dataPoint, provinceTop10) {
  const china = new PolygonLayer({
    autoFit: true,
  })
    .source(data)
    .shape('fill')
    // .color("count", colors)
    .color('count', d => {
      // console.log(provinceTop10, "***889***");
      if (provinceTop10) {
        // 存在排名，前5名排序
        // console.log("provinceTop10", provinceTop10);
        const n = provinceTop10.length;
        return n >= 1 && d >= provinceTop10[0].count
          ? colors[4]
          : n >= 2 && d >= provinceTop10[1].count
          ? colors[3]
          : n >= 3 && d >= provinceTop10[2].count
          ? colors[2]
          : n >= 4 && d >= provinceTop10[3].count
          ? colors[1]
          : colors[0];
      } else {
        // 如果没有排名，则根据d值等级排序
        return d > 100
          ? colors[4]
          : d > 50
          ? colors[3]
          : d > 20
          ? colors[2]
          : d > 0
          ? colors[1]
          : colors[0];
      }
    })
    .style({
      opacity: 1,
    });

  china.on('mousemove', e => {
    // console.log(e, "!!!");
    // 添加popup
    const popup = new Popup({
      offsets: [0, 0],
      closeButton: false,
    })
      .setLnglat(e.lngLat)
      .setHTML(
        `<span style="color:#4d4d4d;">${e.feature.properties.name}: ${
          e.feature.properties.count || 0
        }</span>`
      );
    scene.addPopup(popup);
  });
  // 区域线
  const chinaline = new LineLayer({}).source(data).size(0.2).shape('line').color('#9a9fa3').style({
    opacity: 1,
  });
  // 地图文字
  const pointLayer = new PointLayer({})
    .source(dataPoint, {
      parser: {
        type: 'json',
        coordinates: 'center',
      },
    })
    .shape('name', 'text')
    .size(11)
    .color('#4d4d4d')
    .style({
      stroke: '#ffffff', // 描边颜色
      strokeWidth: 0.5, // 描边宽度
      strokeOpacity: 1.0,
      textAllowOverlap: false,
      fontWeight: 'normal',
    });

  scene.addLayer(china);
  scene.addLayer(chinaline);
  scene.addLayer(pointLayer);
  return [china, chinaline, pointLayer];
}

// 图例，颜色level
// export function addLegend() {
//   const legend = new Control({
//     position: "bottomright",
//   });
//   legend.onAdd = function () {
//     var el = document.createElement("div");
//     el.className = "infolegend legend";
//     var grades = [0, 1, 10, 100, 500, 1000];
//     el.innerHTML += "<h4>图例</h4><span>现存确诊数</span><br>";
//     for (var i = 0; i < grades.length; i++) {
//       el.innerHTML +=
//         '<i style="background:' +
//         colors[i] +
//         '"></i> ' +
//         grades[i] +
//         (grades[i + 1] ? "–" + grades[i + 1] + "<br>" : "+");
//     }
//     return el;
//   };
//   return legend;
// }

// 控制
export function addInfoControl() {
  const info = new Control({
    position: 'topleft',
    name: 'infoControl',
  });
  info.onAdd = function () {
    this._div = document.createElement('div');
    this.update();
    return this._div;
  };

  info.update = function (name) {
    // 业务数据相关
    let html = '<span>全国</span>';
    if (name) {
      html += `<span> &gt; ${name}</span>
          `;
    }
    this._div.innerHTML = `<div class="info_control"><div class="name">${html}</div>
          <div class="note">注：单击省份下钻到市级地图，<br>双击空白处切换到省级地图</div>
          </div>`;
  };
  return info;
}

// 业务数据相关
export function mapInfoContol(provinceTop10) {
  const info = new Control({
    position: 'topright',
    name: 'mapInfoControl',
  });
  info.onAdd = function () {
    this._div = document.createElement('div');
    this.update(provinceTop10);
    return this._div;
  };

  info.update = function (top10) {
    let html = '';
    if (top10) {
      // 城市的数据
      const len = top10.length < 10 ? top10.length : 10;
      for (let i = 0; i < len; i++) {
        html += `<div>${i + 1}.${top10[i].name}：${top10[i].count}</div>`;
      }
    }
    this._div.innerHTML = `<div class='map_info_control'>
    ${html}
  </div>
  `;
  };

  return info;
}

export function addLayerControl(overlayers) {
  const layerContorl = new Layers({
    position: 'topleft',
    overlayers,
  });
  return layerContorl;
}

/**
 * 获取业务数据，数据结构
 */
export function transformData(data) {
  // lab.isaaclin.cn/nCoV/api/area
  // const url = "https://lab.isaaclin.cn/nCoV/api/area?latest=1";
  // const data = await (await fetch(url)).json();

  // mock-后端请求-begin
  // data = [
  //   {
  //     areaCode: 440000,
  //     countryName: "中国", // 国家名称：中国
  //     provinceName: "广东省",
  //     provinceShortName: "广东", // 省份简称：需保持与geo地图上数据一致
  //     count: 54, // 统计展示数据：业务相关，需展示在地图上的数据
  //     cities: [
  //       {
  //         cityName: "广州", // 城市名称：需保持与geo地图上数据一致
  //         count: 50,
  //         areaCode: 440100,
  //       },
  //       {
  //         cityName: "深圳",
  //         count: 4,
  //         areaCode: 440300,
  //       },
  //     ],
  //   },
  //   {
  //     areaCode: 110000,
  //     countryName: "中国", // 国家名称：中国
  //     provinceName: "北京市",
  //     provinceShortName: "北京", // 省份简称：需保持与geo地图上数据一致
  //     count: 954, // 统计展示数据：业务相关，需展示在地图上的数据
  //     cities: [
  //       {
  //         cityName: "丰台区", // 城市名称：需保持与geo地图上数据一致
  //         count: 54,
  //         areaCode: 110106,
  //       },
  //       {
  //         cityName: "海淀区",
  //         count: 900,
  //         areaCode: 110108,
  //       },
  //     ],
  //   },
  //   {
  //     areaCode: 420000,
  //     countryName: "中国",
  //     provinceName: "湖北省",
  //     provinceShortName: "湖北",
  //     count: 133,
  //     cities: [
  //       {
  //         cityName: "武汉",
  //         count: 30,
  //         areaCode: 420100,
  //       },
  //       {
  //         cityName: "孝感",
  //         count: 3,
  //         areaCode: 420900,
  //       },
  //       {
  //         cityName: "荆州",
  //         count: 100,
  //         areaCode: 421000,
  //       },
  //     ],
  //   },
  // ];
  // mock-后端请求-end
  // console.log(data, "地图->1.后端返回-数据");
  const provinceData = [];
  const china = {
    name: '中国',
    count: 0,
  };
  for (let i = 0; i < data.length; i++) {
    const item = data[i];
    if (item.countryName === '中国') {
      const cities = item.cities || [];
      china.count += item.count || 0;
      provinceData.push({
        adcode: parseInt(item.areaCode),
        name: item.provinceShortName,
        count: item.count || 0,
        cities: cities.map(city => {
          return {
            adcode: parseInt(city.areaCode),
            name: city.cityName,
            count: city.count || 0,
          };
        }),
      });
    }
  }
  console.log('中国总数', china.count);
  return provinceData;
}
// 地图数据-业务数据拼接
export function joinData(geo, data) {
  console.log(data, 'joinData--业务拼接数据****');
  const dataObj = {};
  data.forEach(item => {
    // 根据name来拼接，地图地名：省份简称或者城市名称
    // 改为adcode，拼接
    dataObj[item.adcode] = item;
  });
  geo.features = geo.features.map(item => {
    const adcode = item.properties.adcode;
    item.properties = {
      ...item.properties,
      ...dataObj[adcode],
    };
    return item;
  });
  return geo;
}

// 对象数组根据属性排序
export function compare(key) {
  return function (value1, value2) {
    const val1 = value1[key];
    const val2 = value2[key];
    return val2 - val1;
  };
}
